<?php
namespace App\Models\Traits;

use App\Models\User;
use Carbon\Carbon;
use Auth;
use App\Models\MovieWatchUser;

trait MovieWatcher
{
    public function watchings()
    {
        // 正在追的
        return $this->belongsToMany('App\Models\User', 'movie_watch_user')
                    ->withPivot('status')->wherePivot('status', 'watching')
                    ->withTimestamps()->using('App\Models\MovieWatchUser');
    }

    public function watcheds()
    {
        // 已追完的
        return $this->belongsToMany('App\Models\User', 'movie_watch_user')
                    ->withPivot('status')->wherePivot('status', 'watched')
                    ->withTimestamps()->using('App\Models\MovieWatchUser');
    }
    public function watchStatus($user)
    {
        $isWatch = $this->isWatcherBy($user);
        return  $isWatch ? $isWatch->status : false;
    }

    // 最后一次看的时间
    public function last_watched_at($user)
    {
        $last = MovieWatchUser::where('user_id', self::keyId($user))->where('movie_id', $this->id)->first();
        if($last) return $last->updated_at;
        else return false;
    }

    public function isWatcherBy($user)
    {
        return MovieWatchUser::where('user_id', self::keyId($user))->where('movie_id', $this->id)->first() ?: false;
    }

    public function watching($user)
    {
        if ($this->isWatcherBy($user)) {
            $this->updateWatchStatus($user);
        }
        else {
            $this->bingeWatchers()->attach(self::keyId($user), ['status' => 'watching']);
        }
    }
    public function watched($user)
    {
        if ($this->isWatcherBy($user)) {
            $this->updateWatchStatus($user, 'watched');
        }
        else {
            $this->bingeWatchers()->attach(self::keyId($user), ['status' => 'watched']);
        }
        MovieWatchUser::where('user_id', self::keyId($user))->where('movie_id', $this->id)->increment('count');
    }

    public function updateWatchStatus($user, $status = 'watching')
    {
        $this->bingeWatchers()->updateExistingPivot(self::keyId($user), ['status' => $status, 'updated_at' => now()]);
    }

    protected static function keyId($user)
    {
        return !is_a($user, User::class) ? $user : $user->id;
    }
}
